home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C16 / IStack.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.6 KB  |  71 lines

  1. //: C16:IStack.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Simple integer stack
  7. #include "../require.h"
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. class IStack {
  12.   static const int ssize = 100;
  13.   int stack[ssize];
  14.   int top;
  15. public:
  16.   IStack() : top(0) { stack[top] = 0; }
  17.   void push(int i) {
  18.     if(top < ssize) stack[top++] = i;
  19.   }
  20.   int pop() {
  21.     return stack[top > 0 ? --top : top];
  22.   }
  23.   friend class IStackIter;
  24. };
  25.  
  26. // An iterator is a "super-pointer":
  27. class IStackIter {
  28.   IStack& S;
  29.   int index;
  30. public:
  31.   IStackIter(IStack& is)
  32.     : S(is), index(0) {}
  33.   int operator++() { // Prefix form
  34.     if (index < S.top - 1) index++;
  35.     return S.stack[index];
  36.   }
  37.   int operator++(int) { // Postfix form
  38.     int returnval = S.stack[index];
  39.     if (index < S.top - 1) index++;
  40.     return returnval;
  41.   }
  42. };
  43. // For interest, generate Fibonacci numbers:
  44. int fibonacci(int n) {
  45.   const int sz = 100;
  46.   require(n < sz);
  47.   static int f[sz]; // Initialized to zero
  48.   f[0] = f[1] = 1;
  49.   // Scan for unfilled array elements:
  50.   int i;
  51.   for(i = 0; i < sz; i++)
  52.     if(f[i] == 0) break;
  53.   while(i <= n) {
  54.     f[i] = f[i-1] + f[i-2];
  55.     i++;
  56.   }
  57.   return f[n];
  58. }
  59.  
  60. int main() {
  61.   IStack is;
  62.   for(int i = 0; i < 20; i++)
  63.     is.push(fibonacci(i));
  64.   // Traverse with an iterator:
  65.   IStackIter it(is);
  66.   for(int j = 0; j < 20; j++)
  67.     cout << it++ << endl;
  68.   for(int k = 0; k < 20; k++)
  69.     cout << is.pop() << endl;
  70. } ///:~
  71.